class Node<T = number> {
  value: T;
  next: Node<T> | null = null;
  constructor(value: T) {
    this.value = value;
  }
}

class MyLinkedList<T extends number> {
  private head: Node<number> | null = null;
  private size: number = 0;
  constructor() {}

  get(index: number): number {
    if (index < 0 || index >= this.size) return -1;
    let current = this.head;
    let print = 0;
    while (current) {
      if (index === print) return current!.value;
      current = current.next;
      print++;
    }
    return -1;
  }

  addAtHead(val: number): void {
    const newNode = new Node(val);
    let current = this.head;
    if (!this.head) {
      this.head = newNode;
    } else {
      newNode.next = current;
      this.head = newNode;
    }
    this.size++;
  }

  addAtTail(val: number): void {
    const newNode = new Node(val);
    if (!this.head) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = newNode;
    }
    this.size++;
  }

  addAtIndex(index: number, val: number): void {
    if (index < this.size && index > -1) {
      if (index === 0) {
        this.addAtHead(val);
      } else {
        const newNode = new Node(val);
        let current = this.head;
        let previous: Node<number> | null = null;
        let print = 0;
        while (print++ < index && current) {
          previous = current;
          current = current.next;
        }
        newNode.next = current;
        previous!.next = newNode;
      }
      this.size++;
    }
  }

  deleteAtIndex(index: number): void {
    if (index < this.size && index > -1) {
      let current = this.head;
      if (index === 0) {
        this.head = current?.next ?? null;
      } else {
        let previous: Node<number> | null = null;
        let print = 0;
        while (print++ < index && current) {
          previous = current;
          current = current.next;
        }
        previous!.next = current?.next ?? null;
      }
      this.size--;
    }
  }
}
const myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // 链表变为 1->2->3
console.log(myLinkedList.get(1)); // 返回 2
myLinkedList.deleteAtIndex(1); // 现在，链表变为 1->3
console.log(myLinkedList.get(1)); // 返回 3
export {};
